package com.github.tvbox.osc.viewmodel;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class TypeToken<T> {
    private final Type type;
    protected TypeToken() {
        this.type = getTypeTokenTypeArgument();
    }
    public Type getType() {
        return type;
    }
    private Type getTypeTokenTypeArgument() {
        final Type superclass = getClass().getGenericSuperclass();
        if (superclass instanceof ParameterizedType) {
            ParameterizedType parameterized = (ParameterizedType) superclass;
            if (parameterized.getRawType() == TypeToken.class) {
                return parameterized.getActualTypeArguments()[0];
            }
        } else if (superclass == TypeToken.class) {
            throw new IllegalStateException("TypeToken must be created with a type argument: new TypeToken<...>() {}; "
                    + "When using code shrinkers (ProGuard, R8, ...) make sure that generic signatures are preserved.");
        }
        throw new IllegalStateException("Must only create direct subclasses of TypeToken");
    }
}
